// 加载包
const express = require('express')
const uploadmiddleware = require('../controllers/upload')
const multer = require('multer')

// const validate = require('../validator/user')
// const tokenverify = require('../middleware/tokenverify')
const router = express.Router()

// 文章图片、封面存放地址
const articleStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/article/image')
    // ./public/article/image（没有该文件夹，就新建一个）
  },
  filename: function (req, file, cb) {
    // 在这里设定文件名
    cb(null, `${Date.now() + file.originalname}`) // 加上Date.now()可以避免命名重复
  }
})

// 素材图片存放地址
const matterStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/matter/image')
    // 他会放在当前目录下的./public/matter/image 文件夹下（没有该文件夹，就新建一个）
  },
  filename: function (req, file, cb) {
    cb(null, `${Date.now() + file.originalname}`) // 加上Date.now()可以避免命名重复
  }
})
// 文章图片配置
const uploadArticleImg = multer({
  storage: articleStorage
  // fileFilter: (req, file, cb) => {
  //   const filetype = file.mimetype.match(
  //     /(jpeg|jpg|png|gif)$/
  //   )
  //   filetype
  //     ? cb(null, true)
  //     : cb(new Error("I don't have a clue!"))
  // },
  // limits: {
  //   fieldSize: 120
  // }
})
// 素材图片配置
const uploadMatterImg = multer({
  storage: matterStorage,
  fileFilter: (req, file, cb) => {
    const filetype = file.mimetype.match(
      /(jpeg|jpg|png|gif)$/
    )
    filetype
      ? cb(null, true)
      : cb(new Error("I don't have a clue!"))
  },
  limits: {
    fieldSize: 120
  }
})

// 文章图片、封面上传
router.post(
  '/loadarticleimage',
  uploadArticleImg.single('image'),
  uploadmiddleware.uploadArticleImage
)

// 素材图上传
router.post(
  '/loadmatterimage',
  uploadMatterImg.single('image'),
  uploadmiddleware.uploadMatterImage
)

module.exports = router
